//
//  HomeViewController.m
//  DriftDog
//
//  Created by rimi on 15/9/7.
//  Copyright (c) 2015年 廖马林. All rights reserved.
//

#import "HomeViewController.h"
#import "CustomSettingsAlertView.h"
#import <TFHpple.h>
#import "CustomHomeTableViewCell.h"
#import <MJRefresh.h>

static NSString *const headUrl = @"http://news.aigou.com/topchoice/index_";
static NSString *const kCellIdentifier = @"cellIdentifier";

@interface HomeViewController () <UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) NSArray *imageViewsData;  // imageViewData是用来装5个网络图片的信息

@property (nonatomic, strong) UIView *view;
@property (nonatomic, strong) UIScrollView *scrollView;  // 用来放置滚动海报
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) NSMutableDictionary *dataSource;
/* 数据 */
@property (nonatomic, strong) NSMutableArray *imgs;
@property (nonatomic, strong) NSMutableArray *titles;
@property (nonatomic, strong) NSMutableArray *contents;
@property (nonatomic, strong) NSMutableArray *times;

//@property (nonatomic, strong) UIImageView  *firstImageView;    // 图片视图1
//@property (nonatomic, strong) UIImageView  *secondImageView;   // 图片视图2
//@property (nonatomic, strong) UIImageView  *thirdImageView;    // 图片视图3
//@property (nonatomic, strong) UIImageView  *fourthImageView;   // 图片视图4
//@property (nonatomic, strong) UIImageView  *fifthImageView;    // 图片视图5

- (void)initializeUserDataSource;
- (void)initializeUserInterface;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self initializeUserDataSource];
    [self initializeUserInterface];
}

#pragma mark - init

- (void)initializeUserDataSource {
    
    self.index = 1;
    
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[self appendedUrlWithIndext:_index]]];
    TFHpple *doc = [[TFHpple alloc] initWithHTMLData:data];
    NSArray *imgsArrayOne = [doc searchWithXPathQuery:@"/html/body/div[2]/div[2]/div[2]/div[1]/div[1]/ul[1]/li/a[1]/img"];  // 10条信息一组
    NSArray *titlesArrayOne = [doc searchWithXPathQuery:@"/html/body/div[2]/div[2]/div[2]/div[1]/div[1]/ul[1]/li/a[1]"];
    NSArray *contentsArrayOne = [doc searchWithXPathQuery:@"/html/body/div[2]/div[2]/div[2]/div[1]/div[1]/ul[1]/li/p"];
    NSArray *timesArrayOne = [doc searchWithXPathQuery:@"/html/body/div[2]/div[2]/div[2]/div[1]/div[1]/ul[1]/li/span"];
    
    if (imgsArrayOne.count != 0) {
    
        _index ++;  // 参数加1
        
        [self.imgs insertObject:imgsArrayOne atIndex:0];
        [self.titles insertObject:titlesArrayOne atIndex:0];
        [self.contents insertObject:contentsArrayOne atIndex:0];
        [self.times insertObject:timesArrayOne atIndex:0];
        
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
        [dictionary setObject:_imgs forKey:@"imgs"];
        [dictionary setObject:_titles forKey:@"titles"];
        [dictionary setObject:_contents forKey:@"contents"];
        [dictionary setObject:_times forKey:@"times"];
        
        self.dataSource = dictionary;  // 数据源
    }
    
}

- (void)initializeUserInterface {
    
//    [CustomSettingsAlertView showViewWithCustomAlertType:LMLTextFieldType title:@"请输入昵称" complete:^(NSString *name) {
//
//
//    }];
    
    /* 添加父类控件 */
    //[CustomSettingsAlertView showViewWithCustomAlertType:LMLTextFieldType title:@"请输入昵称" complete:^(NSString *name) {
        
        
    //}];
    [self addTitleLabelWithName:@"狗世界"];
    
    
    /* 添加子类控件 */
    [self.view addSubview:self.scrollView];
    [self.view addSubview:self.tableView];
    
    // 添加5张图片在scrollView上面
    for (int i = 0; i < 5; i ++) {
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:DHFlexibleFrame(CGRectMake(i * ORIGIN_WIDTH, 0, ORIGIN_WIDTH, 200), NO)];
        imageView.backgroundColor = [UIColor orangeColor];
        
        [self.scrollView addSubview:imageView];
    }

    
}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 110 * DHFlexibleVerticalMutiplier();
}

// numbers of sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

// numbers of rows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return ((NSArray *) _dataSource[@"imgs"][0]).count;
}

// 配置cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CustomHomeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    
    if (!cell) {
        
        cell = [[CustomHomeTableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:kCellIdentifier];
    }
    // 配置cell
    
    cell.titleLabel.text = [self.dataSource[@"titles"] [indexPath.row] objectForKey:@"title"];  // title
    
    NSString *imageName = [self.dataSource[@"imgs"][indexPath.row] objectForKey:@"src"];  // img
    cell.iconImageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageName]]];
    
    cell.content.text = [self.dataSource[@"contents"][indexPath.row] text];
    
    NSString *timeStr = [self.dataSource[@"times"][indexPath.row] text];
    NSString *newTimeStr = [timeStr substringWithRange:NSMakeRange(0, 10)];
    cell.timeLabel.text = newTimeStr;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - private methods

// 注意：index传1,2,3,4,5,6,7,8 -- 57等
- (NSString *)appendedUrlWithIndext:(NSInteger)index {

    NSString *newUrl = [headUrl stringByAppendingString:[NSString stringWithFormat:@"%ld.htm#news_content_id", index]];
    
    return newUrl;
}

// 请求新的数据
- (void)loadNewData {

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableView.header endRefreshing];
    });
}

// 请求更多的数据
- (void)loadMoreData {

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.tableView.footer endRefreshing];
    });
}

#pragma mark - getter

- (UIScrollView *)scrollView {
    
    if (!_scrollView) {
        
        _scrollView = [[UIScrollView alloc] initWithFrame:DHFlexibleFrame(CGRectMake(0, 75, ORIGIN_WIDTH, 200), NO)];
        
        _scrollView.contentSize = CGSizeMake(5 * CGRectGetWidth(self.view.bounds), 200);
        _scrollView.pagingEnabled = YES;
        _scrollView.backgroundColor = [UIColor lightGrayColor];
        _scrollView.contentOffset = CGPointMake(CGRectGetWidth(self.view.bounds), 0);
        _scrollView.showsHorizontalScrollIndicator = NO; // 设置横向指示器为NO
        _scrollView.delegate = self;  // 设置代理
    }
    return _scrollView;
}

- (UITableView *)tableView  {

    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:DHFlexibleFrame(CGRectMake(0, 75 + 200, ORIGIN_WIDTH, ORIGIN_HEIGHT - 200 - 75 - TAB_HEIGHT), NO) style:UITableViewStylePlain];
        _tableView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        /* 设置MJRefresh */
        _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            // 进入刷新状态后会自动调用这个block
            
        }];
        
        // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
        _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        
        _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            // 进入刷新状态后会自动调用这个block
        }];
        
        // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
        _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
    }
    return _tableView;
}

@end



